#!/usr/bin/env node

import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Large Repository Test Script
 * Tests indexing and search functionality with memory optimizations
 */

// Get command line arguments
const className = process.argv[2];
const memoryLimit = process.argv[3] || '4096'; // Default 4GB

if (!className) {
    console.log('🔍 大型仓库测试脚本');
    console.log('使用方式: node test-large-repo.mjs <className> [memoryMB]');
    console.log('示例: node test-large-repo.mjs ExpandDomain 4096');
    console.log('');
    console.log('内存限制说明:');
    console.log('  - 小型仓库 (<1000 artifacts): 2048MB');
    console.log('  - 中型仓库 (1000-5000 artifacts): 4096MB');
    console.log('  - 大型仓库 (>5000 artifacts): 8192MB');
    process.exit(1);
}

console.log(`🔍 正在搜索类: ${className}`);
console.log(`💾 内存限制: ${memoryLimit}MB`);
console.log(`📁 使用配置文件中的Maven仓库路径`);
console.log('=' + '='.repeat(70));

// MCP request
const mcpRequest = {
    jsonrpc: "2.0",
    id: 1,
    method: "tools/call",
    params: {
        name: "find_class_in_local_repository",
        arguments: {
            className: className
        }
    }
};

// Start MCP server process with memory optimization
const serverProcess = spawn('node', ['dist/index.js'], {
    cwd: __dirname,
    stdio: ['pipe', 'pipe', 'inherit'],
    env: {
        ...process.env,
        NODE_OPTIONS: `--max-old-space-size=${memoryLimit} --expose-gc`
    }
});

let output = '';
let hasReceived = false;
let startTime = Date.now();

// Handle server output
serverProcess.stdout.on('data', (data) => {
    const chunk = data.toString();
    output += chunk;
    
    // Check for complete JSON response
    try {
        const lines = output.split('\n').filter(line => line.trim());
        for (const line of lines) {
            if (line.startsWith('{') && !hasReceived) {
                const response = JSON.parse(line);
                if (response.result && response.result.content) {
                    hasReceived = true;
                    handleResponse(response);
                    serverProcess.kill();
                    return;
                }
            }
        }
    } catch (e) {
        // Continue waiting for more data
    }
});

// Send request to server
serverProcess.stdin.write(JSON.stringify(mcpRequest) + '\n');

// Set longer timeout for large repositories
const timeout = setTimeout(() => {
    console.log('❌ 请求超时 (10分钟)');
    console.log('💡 大型仓库索引可能需要更长时间，请考虑:');
    console.log('   - 增加内存限制: node test-large-repo.mjs ' + className + ' 8192');
    console.log('   - 检查仓库大小: du -sh /path/to/repository');
    console.log('   - 确保足够磁盘空间用于索引文件');
    serverProcess.kill();
    process.exit(1);
}, 600000); // 10 minutes

// Handle response
function handleResponse(response) {
    clearTimeout(timeout);
    const endTime = Date.now();
    const totalTime = endTime - startTime;
    
    try {
        const result = JSON.parse(response.result.content[0].text);
        
        console.log(`⏱️  总处理时间: ${Math.round(totalTime / 1000)}秒`);
        console.log('');
        
        console.log(`📊 仓库统计信息:`);
        console.log(`   📁 仓库路径: ${result.repositoryPath}`);
        console.log(`   ✅ 索引状态: ${result.indexReady ? '已就绪' : '未就绪'}`);
        console.log(`   🗂️  已索引artifacts: ${result.totalArtifactsScanned}`);
        console.log(`   🏷️  已索引类: ${result.totalClassesIndexed}`);
        console.log(`   🔍 搜索结果: ${result.matchesFound} 个匹配`);
        console.log('');
        
        if (result.classes && result.classes.length > 0) {
            console.log(`🎯 匹配结果:`);
            
            result.classes.forEach((classInfo, index) => {
                console.log(`   ${index + 1}. ${classInfo.fullName}`);
                console.log(`      📦 Artifact: ${classInfo.artifact.groupId}:${classInfo.artifact.artifactId}:${classInfo.artifact.version}`);
                console.log(`      📂 路径: ${classInfo.artifact.localPath}`);
                console.log(`      ✅ 反编译: ${classInfo.decompiled ? '成功' : '失败'}`);
                
                if (index < result.classes.length - 1) {
                    console.log('');
                }
            });
            
            // Show first class source code (truncated)
            if (result.classes[0].decompiled && result.classes[0].source) {
                console.log('');
                console.log(`📄 ${result.classes[0].fullName} 源代码预览:`);
                console.log('-'.repeat(80));
                const sourceLines = result.classes[0].source.split('\n');
                const preview = sourceLines.slice(0, 20).join('\n');
                console.log(preview);
                if (sourceLines.length > 20) {
                    console.log(`... (省略${sourceLines.length - 20}行)`);
                }
                console.log('-'.repeat(80));
            }
        } else {
            console.log(`❌ 未找到包含 "${className}" 的类`);
            console.log('💡 提示:');
            console.log('   - 检查类名拼写是否正确');
            console.log('   - 尝试使用部分类名进行搜索');
            console.log('   - 确保Maven仓库路径配置正确');
            console.log('   - 检查仓库是否包含预期的JAR文件');
        }
        
        // Performance metrics
        console.log('');
        console.log(`🚀 性能指标:`);
        console.log(`   ⚡ 搜索方式: ${result.indexReady ? '索引搜索 (高性能)' : '全量扫描 (较慢)'}`);
        console.log(`   💾 内存限制: ${memoryLimit}MB`);
        console.log(`   ⏱️  响应时间: ${Math.round(totalTime / 1000)}秒`);
        
        if (result.totalArtifactsScanned > 1000) {
            console.log('');
            console.log(`📈 大型仓库优化建议:`);
            console.log(`   - 当前仓库规模: ${result.totalArtifactsScanned} artifacts, ${result.totalClassesIndexed} classes`);
            console.log(`   - 索引文件将缓存搜索结果，后续搜索会更快`);
            console.log(`   - 如果频繁OOM，可增加内存: ${Math.max(parseInt(memoryLimit) * 2, 8192)}MB`);
        }
        
    } catch (error) {
        console.log('❌ 解析响应失败:', error.message);
        console.log('原始响应:', response.result.content[0].text);
    }
}

// Handle process errors
serverProcess.on('error', (error) => {
    clearTimeout(timeout);
    console.log('❌ 启动MCP服务器失败:', error.message);
    console.log('💡 请先运行: npm run build');
});

serverProcess.on('exit', (code) => {
    if (code !== 0 && !hasReceived) {
        console.log(`❌ MCP服务器异常退出，代码: ${code}`);
        if (code === 134) { // SIGABRT, often OOM
            console.log('💡 可能是内存不足，尝试增加内存限制:');
            console.log(`   node test-large-repo.mjs ${className} ${Math.max(parseInt(memoryLimit) * 2, 8192)}`);
        }
    }
});